import 'dart:io';

import 'package:app/components/ColorCircle.dart';
import 'package:app/icons/icons.dart';
import 'package:app/model/app_config.dart';
import 'package:app/model/model.dart';
import 'package:app/page/updateColor.dart';
import 'package:app/page/updateImgUrl.dart';
import 'package:app/router/router.dart';
import 'package:app/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:fb_utils/fb_utils.dart';

class AddFormState {
  String childrenId = '';
  String parentId = '';
  final RxString classifyId = ''.obs;
  final RxInt targetTimestamp =
      DateTime.now().toUtc().millisecondsSinceEpoch.obs;
  final RxBool isPrecise = false.obs;
  final RxBool isTop = false.obs;
  final RxBool _isInitialized = false.obs;
  final Rx<Color> eventColor = Rx(StaticAppConfig.defaultEventColor);
  final RxString imgUrl = "".obs;
  final RxDouble blurRadius = 0.0.obs;
  final Rx<Color> textColor = Rx(Colors.black);
  bool get isInitialized => _isInitialized.value;
  set isInitialized(bool value) {
    _isInitialized.value = value;
  }

  void initialize({
    required String name,
    required String parentId,
    required String childrenId,
    required int targetTimestamp,
    required bool isPrecise,
    required bool whetherToTop,
    required Color color,
    required String imgUrl,
    required double blurRadiuss,
    required Color textColors,
  }) {
    this.parentId = parentId;
    this.childrenId = childrenId;
    classifyId.value = parentId;
    this.targetTimestamp.value = targetTimestamp;
    this.isPrecise.value = isPrecise;
    isTop.value = whetherToTop;
    eventColor.value = color;
    this.imgUrl.value = imgUrl;
    eventColor.value = color;
    blurRadius.value = blurRadiuss;
    textColor.value = textColors;
  }
}

class Add extends StatefulWidget with RouterBridge<ChildrenEvent> {
  const Add({super.key});
  @override
  State<Add> createState() => _AddState();
}

class _AddState extends State<Add> {
  final _formState = AddFormState();
  final _textController = TextEditingController();
  final _cList = CountdownEventClassList.create();
  final FocusNode _focusNode = FocusNode();
  late String cacheImageDir;
  static final _minDate = DateTime.utc(1970, 1, 1).millisecondsSinceEpoch;
  static final _maxDate = DateTime.utc(2080, 12, 31).millisecondsSinceEpoch;
  Future<String> _cacheImagePath(String imagePath) async {
    if (cacheImageDir.isEmpty) throw FormatException('cacheImageDir is empty');
    final cacheDir = Directory(cacheImageDir);
    if (!cacheDir.existsSync()) {
      await cacheDir.create();
    }
    final hash = await FbUtils.getMD5WithPath(imagePath);
    final cacheFile = File(
      '${cacheDir.path}/$hash.${imagePath.split('/').last.split(".").last}',
    );
    if (!cacheFile.existsSync()) {
      cacheFile.writeAsBytesSync(File(imagePath).readAsBytesSync());
    }
    return cacheFile.path;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNode.unfocus();
    });
    getApplicationDocumentsDirectory()
        .then((appDocDir) {
          cacheImageDir = '${appDocDir.path}/image_cache';
        })
        .catchError((e) {
          TDToast.showFail(e, context: context);
        });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!_formState.isInitialized) {
      final args = widget.argumentsOf(context);
      if (args != null) {
        _formState.initialize(
          name: args.name.value,
          parentId: args.parentId.value,
          childrenId: args.childrenId.value,
          targetTimestamp: args.targetTimestamp.value,
          isPrecise: args.isprecise.value,
          whetherToTop: args.whetherToTop.value,
          color: args.eventColor.value,
          imgUrl: args.imgUrl.value,
          blurRadiuss: args.blurRadius.value,
          textColors: args.textColor.value,
        );
        _textController.text = args.name.value;
        _formState.isInitialized = true;
      }
    }
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _textController.dispose();
    super.dispose();
  }

  void save() async {
    final countdownEvent =
        _formState.childrenId.isNotEmpty
            ? _cList.findCountdownEventClassById(_formState.parentId)
            : _cList.findCountdownEventClassById(_formState.classifyId.value);

    if (countdownEvent == null) {
      _showMessage('请选择倒计时分类');
      return;
    }

    if (_textController.text.isEmpty) {
      _showMessage('请输入事件名称');
      return;
    }

    if (_formState.childrenId.isEmpty) {
      var imagePath = "";
      if (_formState.imgUrl.value.isNotEmpty) {
        imagePath = await _cacheImagePath(_formState.imgUrl.value);
      }
      countdownEvent.addEventChild(
        name: _textController.text,
        targetTimestamp: _formState.targetTimestamp.value,
        isprecise: _formState.isPrecise.value,
        whetherToTop: _formState.isTop.value,
        eventColor: _formState.eventColor.value,
        imgUrl: imagePath,
        blurRadius: _formState.blurRadius.value,
        textColor: _formState.textColor.value,
      );
    } else {
      _updateExistingEvent(countdownEvent, countdownEvent);
    }

    Navigator.maybePop(context);
  }

  void _showMessage(String content) {
    Fluttertoast.showToast(msg: content);
  }

  void _updateExistingEvent(
    CountdownEventClass countdownEvent,
    CountdownEventClass parentClass,
  ) async {
    final childrenEvent = parentClass.findEventChildById(_formState.childrenId);
    if (childrenEvent == null) {
      _showMessage('事件id错误');
      return;
    }
    if (childrenEvent.imgUrl.value != _formState.imgUrl.value) {
      var oldImagePath = childrenEvent.imgUrl.value;
      await Utils.delteCacheImage(
        _cList.countdownEventList,
        oldImagePath,
        _formState.childrenId,
      );
      if (_formState.imgUrl.value.isNotEmpty) {
        _formState.imgUrl.value = await _cacheImagePath(
          _formState.imgUrl.value,
        );
      }
    }
    if (childrenEvent.parentId.value != _formState.classifyId.value) {
      final error = _cList.moveEventChild(
        _formState.childrenId,
        _formState.parentId,
        _formState.classifyId.value,
      );
      if (error != null) {
        _showMessage(error.toString());
        return;
      }
    }
    childrenEvent.updateChildrenEvent(
      name: _textController.text,
      targetTimestamp: _formState.targetTimestamp.value,
      isprecise: _formState.isPrecise.value,
      whetherToTop: _formState.isTop.value,
      parentId: _formState.classifyId.value,
      eventColor: _formState.eventColor.value,
      imgUrl: _formState.imgUrl.value,
      blurRadius: _formState.blurRadius.value,
      textColor: _formState.textColor.value,
    );
  }

  ChildrenEvent _createChildrenEvent({imgurl = ""}) {
    Map<String, dynamic> dartMap = {
      "childrenId": "",
      "name": _textController.text,
      "parentId": "2",
      "targetTimestamp": _formState.targetTimestamp.value,
      "isprecise": false,
      "whetherToTop": false,
      "eventColor": _formState.eventColor.value.toARGB32(),
      "imgUrl": imgurl == "" ? _formState.imgUrl.value : imgurl,
      "blurRadius": 0.0,
      "textColor": _formState.textColor.value.toARGB32(),
    };
    return ChildrenEvent.fromJson(dartMap);
  }

  void delete() {
    showGeneralDialog(
      context: context,
      pageBuilder: (
        BuildContext buildContext,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return TDAlertDialog(
          content: '确定删除${_textController.text}吗？',
          rightBtnAction: () async {
            final countdownEvent = _cList.findCountdownEventClassById(
              _formState.classifyId.value,
            );
            if (countdownEvent == null) {
              _showMessage('请选择倒计时分类');
              return;
            }
            if (_textController.text.isEmpty) {
              _showMessage('请输入事件名称');
              return;
            }

            var childEvent = countdownEvent.findEventChildById(
              _formState.childrenId,
            );
            if (childEvent != null && childEvent.imgUrl.value.isNotEmpty) {
              await Utils.delteCacheImage(
                _cList.countdownEventList,
                childEvent.imgUrl.value,
                _formState.childrenId,
              );
            }
            countdownEvent.deleteEventChild(_formState.childrenId);

            Navigator.of(context).pop();
            Navigator.of(context).popUntil((route) => route.isFirst);
          },
          leftBtnAction: () => Navigator.of(buildContext).pop(),
        );
      },
    );
  }

  Widget spacer({double height = 10}) {
    return SizedBox(height: height);
  }

  Widget item({
    IconData? icon,
    String? text,
    List<Widget>? children,
    VoidCallback? onTap,
  }) {
    List<Widget> childrenArr = [];
    if (icon != null) {
      childrenArr.addAll([Icon(icon), const SizedBox(width: 5)]);
    }
    if (text != null) {
      childrenArr.addAll([
        Text(text, style: TextStyle(fontSize: 18)),
        const SizedBox(width: 5),
      ]);
    }
    if (children != null) {
      childrenArr.addAll(children);
    }
    return GestureDetector(
      onTap: onTap ?? () {},
      child: Container(
        height: 60,
        decoration: BoxDecoration(color: Colors.white),
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 15),
        child: Row(children: childrenArr),
      ),
    );
  }

  Widget menu() {
    if (_formState.classifyId.value.isEmpty &&
        _cList.countdownEventList.isNotEmpty) {
      _formState.classifyId.value = _cList.countdownEventList.first.id.value;
    }
    return Expanded(
      child: Obx(
        () => TDDropdownMenu(
          direction: TDDropdownMenuDirection.down,
          items: [
            TDDropdownItem(
              options:
                  _cList.countdownEventList.map((item) {
                    if (item.id.value == _formState.classifyId.value) {
                      return TDDropdownItemOption(
                        label: item.name.value,
                        value: item.id.value,
                        selected: true,
                      );
                    }
                    return TDDropdownItemOption(
                      label: item.name.value,
                      value: item.id.value,
                    );
                  }).toList(),
              onChange: (value) {
                _formState.classifyId.value = value[0];
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget topSwitch() {
    return item(
      icon: TDIcons.align_top,
      text: "置顶",
      children: [
        Expanded(
          child: Container(
            alignment: Alignment.centerRight,
            padding: EdgeInsets.only(right: 20),
            child: Obx(
              () => TDSwitch(
                isOn: _formState.isTop.value,
                size: TDSwitchSize.large,
                onChanged: (value) {
                  _formState.isTop.value = value;
                  return value;
                },
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget preciseSwitch() {
    return item(
      icon: TDIcons.time,
      text: "精确计时",
      children: [
        Expanded(
          child: Container(
            alignment: Alignment.centerRight,
            padding: EdgeInsets.only(right: 20),
            child: Obx(
              () => TDSwitch(
                isOn: _formState.isPrecise.value,
                size: TDSwitchSize.large,
                onChanged: (value) {
                  _formState.isPrecise.value = value;
                  return value;
                },
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget switchEventColor() {
    return item(
      icon: TDIcons.color_invert,
      text: "事件颜色",
      onTap: () {
        context
            .routeOf<UpdateColor>()
            .arguments(_createChildrenEvent())
            .to()
            .then((value) {
              try {
                if (value != null) {
                  var a = value as Color;
                  _formState.eventColor.value = a;
                }
              } catch (e) {
                _showMessage(e.toString());
              }
            });
      },
      children: [
        Expanded(
          child: Container(
            padding: EdgeInsets.only(right: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Obx(() => ColorCircle(color: _formState.eventColor.value)),
                const SizedBox(width: 3),
                const Icon(TDIcons.caret_right_small),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget calendar() {
    final size = MediaQuery.of(context).size;
    return item(
      icon: TDIcons.calendar_1,
      text: "目标日",
      children: [
        Obx(
          () => Text(
            Utils.formatDate(
              _formState.targetTimestamp.value,
              "yyyy-MM-dd E HH:mm:ss",
            ),
            style: TextStyle(fontSize: 16),
          ),
        ),
      ],
      onTap: () {
        TDCalendarPopup(
          context,
          visible: true,
          onConfirm: (value) {
            _formState.targetTimestamp.value = value[0];
          },
          child: TDCalendar(
            title: '请选择日期和时间',
            height: size.height * 0.75,
            cellHeight: 50,
            pickerHeight: 100,
            useTimePicker: true,
            minDate: _minDate,
            maxDate: _maxDate,
            value: [_formState.targetTimestamp.value],
          ),
        );
      },
    );
  }

  Widget imgUrlInput() {
    return item(
      icon: TDIcons.image,
      text: "背景图",
      onTap: () async {
        final imageEntitys = await AssetPicker.pickAssets(
          context,
          pickerConfig: const AssetPickerConfig(
            maxAssets: 1,
            requestType: RequestType.image,
            textDelegate: AssetPickerTextDelegate()
          ),
        );
        if (imageEntitys == null || imageEntitys.isEmpty) return;
        final imageFile = await imageEntitys.first.file;
        if (imageFile == null) return;
        var res =
            await context
                .routeOf<UpdateImgurl>()
                .arguments(_createChildrenEvent(imgurl: imageFile.path))
                .to();
        try {
          if (res != null) {
            var a = res as ChildrenEvent;
            _formState.imgUrl.value = a.imgUrl.value;
            _formState.blurRadius.value = a.blurRadius.value;
            _formState.textColor.value = a.textColor.value;
          }
        } catch (e) {
          _showMessage(e.toString());
        }
      },
      children: [
        Expanded(
          child: Container(
            padding: EdgeInsets.only(right: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Obx(() {
                  if (_formState.imgUrl.value.isEmpty) return Text('未选择图片');
                  return Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8.0),
                        child: Image(
                          image: FileImage(File(_formState.imgUrl.value)),
                          width: 50,
                          height: 50,
                          fit: BoxFit.cover,
                        ),
                      ),
                      const SizedBox(width: 3),
                      GestureDetector(
                        onTap: () {
                          _formState.imgUrl.value = "";
                          _formState.blurRadius.value = 0;
                          _formState.textColor.value = Colors.black;
                        },
                        child: Icon(TDIcons.delete, color: Colors.red),
                      ),
                    ],
                  );
                }),
                const SizedBox(width: 3),
                const Icon(TDIcons.caret_right_small),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget buttons() {
    return Expanded(
      child: Column(
        children: [
          TDButton(
            text: '保存',
            size: TDButtonSize.large,
            type: TDButtonType.fill,
            theme: TDButtonTheme.primary,
            isBlock: true,
            onTap: save,
          ),
          if (_formState.childrenId.isNotEmpty) ...[
            spacer(),
            TDButton(
              text: '删除',
              size: TDButtonSize.large,
              type: TDButtonType.fill,
              theme: TDButtonTheme.danger,
              isBlock: true,
              onTap: delete,
            ),
          ],
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: TDNavBar(
        height: 48,
        title: _formState.childrenId.isEmpty ? "添加倒计时" : '修改倒计时',
        titleColor: Colors.white,
        centerTitle: false,
        backgroundColor: StaticAppConfig.appBarColor,
        titleFontWeight: FontWeight.w600,
        useDefaultBack: false,
        screenAdaptation: true,
        leftBarItems: [
          TDNavBarItem(
            icon: Icons.chevron_left,
            iconColor: Colors.white,
            action: () {
              Navigator.maybePop(context);
            },
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(color: Color(0xFFCCCCCC)),
        child: Column(
          children: [
            spacer(),
            item(
              icon: AppIcons.event,
              text: "事件名称",
              children: [
                Expanded(
                  child: TDInput(
                    hintText: '输入事件名称',
                    needClear: false,
                    controller: _textController,
                    focusNode: _focusNode,
                    onTapOutside: (event) {
                      _focusNode.unfocus();
                    },
                    onChanged: (text) {
                      _textController.text = text;
                    },
                  ),
                ),
              ],
            ),
            spacer(),
            calendar(),
            spacer(),
            item(
              icon: TDIcons.address_book,
              text: "倒数本",
              children: [
                const Expanded(flex: 3, child: SizedBox.shrink()),
                menu(),
                const SizedBox(width: 10),
              ],
            ),
            spacer(),
            topSwitch(),
            spacer(),
            preciseSwitch(),
            spacer(),
            switchEventColor(),
            spacer(),
            imgUrlInput(),
            spacer(),
            buttons(),
          ],
        ),
      ),
    );
  }
}
